
package com.huawei.housekeeper.config.filter;

import com.huawei.housekeeper.enums.ErrorCode;
import com.huawei.housekeeper.result.Result;
import com.huawei.housekeeper.utils.JsonUtil;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 无权限访问处理
 *
 * @author lWX1128557
 * @since 2022-03-22
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JsonUtil.objectToJson(Result.createResult(ErrorCode.FORBIDDEN)));
        httpServletResponse.setStatus(403);
        httpServletResponse.getWriter().flush();
    }
}
